﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.Web.Areas.SafetyConstruction.ViewModels;
using KingRoad.EPM.Web.Areas.SafetyConstruction.SafetyConstructionFramework.Common;

using KingRoad.EPM.SafetyManagementEntity.Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System.IO;
using System.Text;

namespace KingRoad.EPM.Web.Areas.SafetyConstruction.Controllers
{
    public class ScmPotentialAdviceController : BaseController
    {
        public const string RYGL_SGRY = "RYGL_YHZGTZS";
        // GET: /ScmPotentialAdvice/
        /// <summary>
        /// 隐患整改通知书台账 SafetyConstruction.ScmPotentialAdvice.PotentialAdviceList
        /// </summary>
        /// <returns></returns>
        public ActionResult PotentialAdviceList(string pageName)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var list = ScmPotentialadviceUIRule.GetPotentialadviceForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Pa_Date", out totalRecord, "");

            int tempTotalRecord = 0;
            var allList = ScmPotentialadviceUIRule.GetPotentialadviceForSearch(1, ALL_RECORD_ITEMS, "Pa_Date", out tempTotalRecord, "");
            SetSectionValue(RYGL_SGRY, allList);

            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            //return View(new PotentialAdviceViewModel { PotentialAdviceList = list });
            return String.IsNullOrEmpty(pageName) ? View(new PotentialAdviceViewModel { PotentialAdviceList = list }) : View(pageName, new PotentialAdviceViewModel { PotentialAdviceList = list });


        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPage(PotentialAdviceViewModel vm)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return PotentialAdviceList("PotentialAdviceList");
            ViewBag.contract = Request.Form["contract"];
            ViewBag.date = Request.Form["date"];
            string sql = " 1=1 ";
            if (ViewBag.contract != "")
                sql += " and Pa_Section like '%" + ViewBag.contract + "%' ";
            if (ViewBag.date != "")
                sql += " and Pa_Date ='" + ViewBag.date + "' or Pa_ReplyDate='" + ViewBag.date + "' ";

            var list = ScmPotentialadviceUIRule.GetPotentialadviceForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Pa_Date", out totalRecord, sql);

            int tempTotalRecord = 0;
            var allList = ScmPotentialadviceUIRule.GetPotentialadviceForSearch(1, ALL_RECORD_ITEMS, "Pa_Date", out tempTotalRecord, sql);
            SetSectionValue(RYGL_SGRY, allList);

            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("PotentialAdviceList", new PotentialAdviceViewModel { PotentialAdviceList = list });
        }
        /// <summary>
        /// 台账-添加 
        /// 功能：显示添加页面
        /// </summary>
        /// <returns></returns>
        public ActionResult  PotentialAdviceAdd()
        {
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "是", Value = "True" });
            list.Add(new SelectListItem { Text = "否", Value = "False" });
            ViewBag.list = list;
            return View();
        }
        /// <summary>
        /// 台账-添加 
        /// 功能：执行添加操作
        /// </summary>
        /// <returns></returns>
        public JsonResult  PotentialAdviceAddData(PotentialAdviceViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.PotentialAdviceInfo.Pa_ID = Guid.NewGuid().ToString();
                vm.PotentialAdviceInfo.Pa_Time = DateTime.Now;
                vm.PotentialAdviceInfo.Pa_UserID = GetLoginUserId;              //操作人ID及名称 添加权限时赋值
                vm.PotentialAdviceInfo.Pa_UserName = GetLoginUserRealName;
                int info = ScmPotentialadviceUIRule.AddPotentialadvice(vm.PotentialAdviceInfo);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    navTabId = "SafetyConstruction.ScmPotentialAdvice.PotentialAdviceList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
      
        /// <summary>
        /// 台账-批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult PotentialAdviceMultiDelete(string id)
        {
            dynamic jsonReturn = new ExpandoObject();
      //      var ids = base.GetRequestFormValue<string>("ids");
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                int info = ScmPotentialadviceUIRule.DeletePotentialadviceMulti(id);
            });

            //保存成功
            if (true)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "SafetyConstruction.ScmPotentialAdvice.PotentialAdviceList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 台账——编辑
        /// 功能：根据id加载相对应数据
        /// </summary>
        /// <returns></returns>
        public ActionResult PotentialAdviceEdit(Guid id)
        {
            var info = ScmPotentialadviceUIRule.GetPotentialadviceByID(id);
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "是", Value = "True" });
            list.Add(new SelectListItem { Text = "否", Value = "False" });
            ViewBag.list = list;

            return View(new PotentialAdviceViewModel { PotentialAdviceInfo = info });
        }
        /// <summary>
        /// 台账-编辑（保存工作） 
        /// 功能：执行保存数据
        /// </summary>
        /// <returns></returns>
        public JsonResult PotentialAdviceEditData(PotentialAdviceViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.PotentialAdviceInfo.Pa_Time = DateTime.Now;
                vm.PotentialAdviceInfo.Pa_UserID = GetLoginUserId;              //操作人ID及名称 添加权限时赋值
                vm.PotentialAdviceInfo.Pa_UserName = GetLoginUserRealName;
                int info = ScmPotentialadviceUIRule.UpdatePotentialadvice(vm.PotentialAdviceInfo);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "更新成功",
                    navTabId = "SafetyConstruction.ScmPotentialAdvice.PotentialAdviceList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "更新失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 台账——查看
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public ActionResult PotentialAdviceDetail(Guid id)
        {
            var info = ScmPotentialadviceUIRule.GetPotentialadviceByID(id);
            return View(new PotentialAdviceViewModel { PotentialAdviceInfo = info });
        }


        #region Excel导入、导出
        /// <summary>
        /// Excel导出
        /// </summary>
        /// <returns></returns>
        public FileResult Excel()
        {
            //获取list数据           
         //   var list =ScmPotentialadviceUIRule.GetAllPotentialadvice();
            var list = GetSessionValue<List<ScmPotentialadviceInfo>>(RYGL_SGRY);

            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //列宽度
            sheet1.SetColumnWidth(0, 5 * 256);
            sheet1.SetColumnWidth(1, 15 * 256);
            sheet1.SetColumnWidth(2, 15 * 256);
            sheet1.SetColumnWidth(3, 15 * 256);
            sheet1.SetColumnWidth(4, 15 * 256);
            sheet1.SetColumnWidth(5, 15 * 256);
            sheet1.SetColumnWidth(6, 15 * 256);
            sheet1.SetColumnWidth(7, 15 * 256);
            sheet1.SetColumnWidth(8, 15 * 256);
            sheet1.SetColumnWidth(9, 15 * 256);
            //设置第一行
            IRow row0 = sheet1.CreateRow(0);
            //行高
            row0.Height = 30 * 20;
            //合并单元格
            sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 9));
            //创建单元格
            CreateCell(row0, 0, Getcellstyle(book, "center", false, 14, 300), "隐患整改通知书台账");
            //给sheet1添加第二行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(1);
            //行高
            row1.Height = 25 * 20;
            CreateCell(row1, 0, Getcellstyle(book, "center", true, 11, 600), "序号");
            CreateCell(row1, 1, Getcellstyle(book, "center", true, 11, 600), "合同段");
            CreateCell(row1, 2, Getcellstyle(book, "center", true, 11, 600), "日期");
            CreateCell(row1, 3, Getcellstyle(book, "center", true, 11, 600), "编号");
            CreateCell(row1, 4, Getcellstyle(book, "center", true, 11, 600), "检查地点");
            CreateCell(row1, 5, Getcellstyle(book, "center", true, 11, 600), "安全隐患");
            CreateCell(row1, 6, Getcellstyle(book, "center", true, 11, 600), "监理审核回复（是/否）");
            CreateCell(row1, 7, Getcellstyle(book, "center", true, 11, 600), "回复日期");
            CreateCell(row1, 8, Getcellstyle(book, "center", true, 11, 600), "整改情况");
            CreateCell(row1, 9, Getcellstyle(book, "center", true, 11, 600), "备注");

            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 2);
                CreateCell(rowtemp, 0, Getcellstyle(book), (i + 1).ToString());
                CreateCell(rowtemp, 1, Getcellstyle(book), list[i].Pa_Section);
                CreateCell(rowtemp, 2, Getcellstyle(book), list[i].Pa_Date==null?"":Convert.ToDateTime(list[i].Pa_Date).ToString("yyyy-MM-dd"));
                CreateCell(rowtemp, 3, Getcellstyle(book), list[i].Pa_Number);
                CreateCell(rowtemp, 4, Getcellstyle(book), list[i].Pa_Location);
                CreateCell(rowtemp, 5, Getcellstyle(book), list[i].Pa_Problem);
                CreateCell(rowtemp, 6, Getcellstyle(book), list[i].Pa_IsCheck==false?"否":"是");
                CreateCell(rowtemp, 7, Getcellstyle(book), list[i].Pa_ReplyDate==null?"":Convert.ToDateTime(list[i].Pa_ReplyDate).ToString("yyyy-MM-dd"));
                CreateCell(rowtemp, 8, Getcellstyle(book), list[i].Pa_Correct);
                CreateCell(rowtemp, 9, Getcellstyle(book), list[i].Pa_Remark);
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            string fileName = HttpUtility.UrlEncode("隐患整改通知书台账.xls", Encoding.GetEncoding("UTF-8"));
            return File(ms, "application/vnd.ms-excel", fileName);

        }
        /// <summary>
        /// Excel导入
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public JsonResult ImportExcelFile(HttpPostedFileBase FileData)
        {
            string infor = "";
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                if (FileData != null)
                {
                    string tempFileName = FileData.FileName;
                    string fileExt = Path.GetExtension(tempFileName).ToLower();
                    string fileName = Guid.NewGuid().ToString() + fileExt;
                    string tempPath = "/TempleterFilePath";
                    if (!tempPath.EndsWith("/"))
                        tempPath += "/";
                    tempPath = Server.MapPath(tempPath);
                    if (!Directory.Exists(tempPath))
                        Directory.CreateDirectory(tempPath);
                    tempPath = Path.Combine(tempPath, fileName);
                    FileData.SaveAs(tempPath);
                    if (string.IsNullOrWhiteSpace(tempPath) || !System.IO.File.Exists(tempPath))
                    {
                        throw new Exception("导入文件不存在");
                    }

                    HSSFWorkbook hssfworkbook;
                    //读取文件流
                    using (FileStream fs = System.IO.File.OpenRead(tempPath))
                    {
                        hssfworkbook = new HSSFWorkbook(fs);

                        //获取第一个工作簿
                        NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
                        {
                            var ret = ExcelImportValidation.Validation<ScmPotentialadviceInfo>(sheet);
                            if (ret.Item1)
                            {
                                //获取第一行
                                IRow headerRow = sheet.GetRow(0);
                                //列数
                                int cellCount = headerRow.LastCellNum;
                                //行数 
                                int rowCount = sheet.LastRowNum;
                                //循环行
                                for (int i = 1; i <= rowCount; i++)
                                {
                                    IRow row = sheet.GetRow(i);
                                    //隐患整改通知书台账
                                    ScmPotentialadviceInfo info = new ScmPotentialadviceInfo();
                                    info.Pa_ID = Guid.NewGuid().ToString();
                                    info.Pa_Time = DateTime.Now;
                                    //操作人ID及名称 添加权限时赋值
                                    info.Pa_UserID = GetLoginUserId;
                                    info.Pa_UserName = GetLoginUserRealName;
                                    //读取该行信息
                                    info.Pa_Section = GetCellValue(row.GetCell(0));
                                    var unitidInfo = GetUnitInfoByCode(info.Pa_Section);
                                    info.Pa_UnitID = unitidInfo.UNIT_ID;
                                    info.Pa_UnitName = unitidInfo.UNIT_NAME;
                                    if (string.IsNullOrEmpty(GetCellValue(row.GetCell(1))))
                                    {
                                        info.Pa_Date = null;
                                    }
                                    else
                                    {
                                        info.Pa_Date = Convert.ToDateTime(GetCellValue(row.GetCell(1)));
                                    }
                                    info.Pa_Number = GetCellValue(row.GetCell(2));
                                    info.Pa_Location = GetCellValue(row.GetCell(3));


                                    info.Pa_Problem = GetCellValue(row.GetCell(4));


                                    //info.Pa_Problem = GetCellValue(row.GetCell(4));
                                    info.Pa_IsCheck = GetCellValue(row.GetCell(5)) == "是" ? true : false;
                                    if (string.IsNullOrEmpty(GetCellValue(row.GetCell(6))))
                                    {
                                        info.Pa_ReplyDate = null;
                                    }
                                    else
                                    {
                                        info.Pa_ReplyDate = Convert.ToDateTime(GetCellValue(row.GetCell(6)));
                                    }
                                    info.Pa_Correct = GetCellValue(row.GetCell(7));
                                    info.Pa_Remark = GetCellValue(row.GetCell(8));
                                    //向数据库插入数据 
                                    ScmPotentialadviceUIRule.AddPotentialadvice(info);
                                }
                            }
                            else
                            {
                                infor = ret.Item2;
                            }

                        }
                    }
                    //删除临时文件
                    System.IO.File.Delete(tempPath);
                }
            });
            dynamic jsonReturn = new ExpandoObject();
            //保存成功
            if (isScuess)
            {
                if (infor == "")
                {
                    jsonReturn = new
                    {
                        statusCode = "200",
                        message = "导入成功",
                        navTabId = "",
                        rel = "",
                        callbackType = "",
                        forwardUrl = "",
                        confirmMsg = ""
                    };
                }
                else
                {
                    jsonReturn = new
                    {
                        statusCode = "300",
                        message = "导入失败!  " + infor,
                    };
                }
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "导入失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };

        }
        //public JsonResult ImportExcelFile(int[] datas)
        //{
        //    string infor = "";
        //    var isScuess = TryCatchCommand.TryExec(() =>
        //    {
        //        if (datas != null)
        //        {
        //            HSSFWorkbook hssfworkbook;
        //            var bytes = datas.ToList().ConvertAll(x => (byte)x).ToArray();
        //            //读取文件流
        //            using (Stream file = new MemoryStream(bytes))
        //            {
        //                hssfworkbook = new HSSFWorkbook(file);
        //            }
        //            //获取第一个工作簿
        //            NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
        //            {
        //                var ret = ExcelImportValidation.Validation<ScmPotentialadviceInfo>(sheet);
        //                if (ret.Item1)
        //                {
        //                    //获取第一行
        //                    IRow headerRow = sheet.GetRow(0);
        //                    //列数
        //                    int cellCount = headerRow.LastCellNum;
        //                    //行数 
        //                    int rowCount = sheet.LastRowNum;
        //                    //循环行
        //                    for (int i = 1; i <= rowCount; i++)
        //                    {
        //                        IRow row = sheet.GetRow(i);
        //                        //隐患整改通知书台账
        //                        ScmPotentialadviceInfo info = new ScmPotentialadviceInfo();
        //                        info.Pa_ID = Guid.NewGuid().ToString();
        //                        info.Pa_Time = DateTime.Now;
        //                        //操作人ID及名称 添加权限时赋值
        //                        info.Pa_UserID = GetLoginUserId;
        //                        info.Pa_UserName = GetLoginUserRealName;
        //                        //读取该行信息
        //                        info.Pa_Section = GetCellValue(row.GetCell(0));
        //                        var unitidInfo = GetUnitInfoByCode(info.Pa_Section);
        //                        info.Pa_UnitID = unitidInfo.UNIT_ID;
        //                        info.Pa_UnitName = unitidInfo.UNIT_NAME;
        //                        if (string.IsNullOrEmpty(GetCellValue(row.GetCell(1))))
        //                        {
        //                            info.Pa_Date = null;
        //                        }
        //                        else
        //                        {
        //                            info.Pa_Date = Convert.ToDateTime(GetCellValue(row.GetCell(1)));
        //                        }
        //                        info.Pa_Number = GetCellValue(row.GetCell(2));
        //                        info.Pa_Location = GetCellValue(row.GetCell(3));


        //                        info.Pa_Problem = GetCellValue(row.GetCell(4));


        //                        //info.Pa_Problem = GetCellValue(row.GetCell(4));
        //                        info.Pa_IsCheck = GetCellValue(row.GetCell(5)) == "是" ? true : false;
        //                        if (string.IsNullOrEmpty(GetCellValue(row.GetCell(6))))
        //                        {
        //                            info.Pa_ReplyDate = null;
        //                        }
        //                        else
        //                        {
        //                            info.Pa_ReplyDate = Convert.ToDateTime(GetCellValue(row.GetCell(6)));
        //                        }
        //                        info.Pa_Correct = GetCellValue(row.GetCell(7));
        //                        info.Pa_Remark = GetCellValue(row.GetCell(8));
        //                        //向数据库插入数据 
        //                        ScmPotentialadviceUIRule.AddPotentialadvice(info);
        //                    } 
        //                }
        //                else
        //                {
        //                    infor = ret.Item2;
        //                }
                     
        //            }
        //        }
        //    });
        //    dynamic jsonReturn = new ExpandoObject();
        //    //保存成功
        //    if (isScuess)
        //    {
        //        if (infor == "")
        //        {
        //            jsonReturn = new
        //            {
        //                statusCode = "200",
        //                message = "导入成功",
        //                navTabId = "",
        //                rel = "",
        //                callbackType = "",
        //                forwardUrl = "",
        //                confirmMsg = ""
        //            };
        //        }
        //        else
        //        {
        //            jsonReturn = new
        //            {
        //                statusCode = "300",
        //                message = "导入失败!  " + infor,
        //            };  
        //        }
        //    }
        //    else
        //    {
        //        jsonReturn = new
        //        {
        //            statusCode = "300",
        //            message = "导入失败",
        //        };
        //    }
        //    return new JsonResult()
        //    {
        //        Data = jsonReturn
        //    };

        //}
        #endregion

    }
}
